/** 系统设置**/
// 1报告打印机 2凭条打印机 3身份证读卡器
export class SystemSet{
    constructor() {
        this.name = 'SystemController';
        this.sysexecute = null;
    }
    async InitAsync() {
        if(typeof(CefSharp) == 'undefined') {
            console.error("CefSharp is undefined.")
            throw "CefSharp is undefined.";
        } else {
            if(typeof(CmdBroker) == 'undefined') {
                await CefSharp.BindObjectAsync(this.name);

            }
        }
        this.sysexecute = SystemController;
    }
    /**
     * 设置系统时间
     * @param {data} YYYYMMDDHHMMSS
     */
    async SysSetTime(data) {
        if(this.sysexecute == null) {
            await this.InitAsync();
        }
        await this.sysexecute.setSysTime(data)
    }
        /**
     * 系统重启
     */
    async SysRestart() {
        if(this.sysexecute == null) {
            await this.InitAsync();
        }
        await this.sysexecute.restart();
    }
      /**
     * 系统关机
     */
    async SysShutDown() {
        if(this.sysexecute == null) {
            await this.InitAsync();
        }
        await this.sysexecute.shutDown();
    }

	/**
	 * 获取IPV4地址
	 */
	async  doInterface(){
		if(this.sysexecute == null) {
		    await this.InitAsync();
		}
	   await CefSharp.BindObjectAsync('SystemController');
	   var json = SystemController.getIPV4Address();
	   let str = JSON.parse(json)
	   return str;
	}
}
/** 调用exe**/
export class CallExe{
    constructor() {
        this.name = 'CmdBroker';
        this.sprinter = null;
    }
    async InitAsync() {
        if(typeof(CefSharp) == 'undefined') {
            console.error("CefSharp is undefined.")
            throw "CefSharp is undefined.";
        } else {
            if(typeof(CmdBroker) == 'undefined') {
                await CefSharp.BindObjectAsync(this.name);
            }
        }

        this.sprinter = CmdBroker;
    }

    async OpenExe(target,workDir,args) {
        await this.InitAsync();
        await this.sprinter.execute(target, workDir,args)
        // let ret = await  this.sprinter.execute(target, workDir,args)
        // if (!ret) {
        //     LogError(`调用${workDir}失败`);
        //     throw new Error(`调用${workDir}失败`);
        // }
    }
}
//打印机
export class SimplerPrinter {
    constructor() {
        this.printer = null;
        this.name = "SimplePrinter";
    }

    async InitAsync() {
		let initedSimplePrinter = false;
        if (initedSimplePrinter == false) {
            if(CefSharp == undefined) {
                console.error("CefSharp is undefined.")
                throw "CefSharp is undefined.";
            } else {
                initedSimplePrinter = true;
                await CefSharp.BindObjectAsync(this.name);
				console.log('!!')
				console.log(SimplePrinter,'SimplePrinter')
                this.printer = SimplePrinter;
            }
        } else {
            this.printer = SimplePrinter;
        }
    }

    async PrintFromFtp(url, user, password, print_to) {
        await this.InitAsync();
        return await this.printer.printFromFtp(url, user, password, print_to);
    }

    async PrintFromHttp(url, print_to) {
        await this.InitAsync();
        return await this.printer.printFromHttp(url, print_to);
    }

    async PrintImageFromUrl(url, print_to) {
        await this.InitAsync();
        return await this.printer.printImageFromUrl(url, print_to);
    }
}
/** 讯普热敏打印机 */
export class SiupoSlipPrinter {
    constructor() {
        let terminfo=sessionStorage.getItem("terminfo");
        let termjson=JSON.parse(terminfo);
		console.log(termjson,'termjson')
        for( let item of termjson) {
            if(item.deviceType=="2"){
              console.log(item);
              this.port=item.port;
              this.baudrate=parseInt(item.bps);
              break;
            }
         }
		// this.port='COM1';
		// this.baudrate=38400;
        this.printer = null;
        this.name = 'SiupoPrinter'
    }

    async InitAsync() {
        if(typeof(CefSharp) == 'undefined') {
            console.error("CefSharp is undefined.")
            throw "CefSharp is undefined.";
        } else {
            if(typeof(SiupoPrinter) == 'undefined') {
                await CefSharp.BindObjectAsync(this.name);
            }
        }
        this.printer = SiupoPrinter;
    }

    async Open() {
        await this.InitAsync();
        let ret = await this.printer.open(this.port, this.baudrate, 0);
        if (!ret) {
            LogError(`打开串口${this.port}失败`);
            throw new Error(`打开串口${this.port}失败`);
        }
    }

    async Close() {
        let ret = await this.printer.close();
        if(!ret) {
            throw new Error('SiupoPrinter Close error');
        }
    }

    async Reset() {
        if(this.printer == null) {
            await this.InitAsync();
        }
        let ret = await this.printer.reset();
        if(!ret) {
            throw new Error('SiupoPrinter Reset error');
        }
    }

    /**
     * 设置页面左边距
     * @param {number} n 页面左边距(单位 0.125mm)
     */
    async SetLeftMargin(n) {
        if(this.printer == null) {
            await this.InitAsync();
        }
        let ret = await this.printer.setLeftMargin(n);
        if(!ret) {
            throw new Error('SiupoPrinter SetLeftMargin error');
        }
    }

    /**
     * 设置页面右边距
     * @param {number} n 页面右边距(单位 0.125mm)
     */
    async SetRightMargin(n) {
        if(this.printer == null) {
            await this.InitAsync();
        }
        let ret = await this.printer.setRightMargin(n);
        if(!ret) {
            throw new Error('SiupoPrinter SetRightMargin error');
        }
    }

    async SetFontSize(width, height) {
        if(this.printer == null) {
            await this.InitAsync();
        }
        let ret = await this.printer.setFontSize(width, height);
        if(!ret) {
            throw new Error('SiupoPrinter SetFontSize error');
        }
    }

    async SetBold(b) {
        if(this.printer == null) {
            await this.InitAsync();
        }
        let ret = await this.printer.setBold(b);
        if(!ret) {
            throw new Error('SiupoPrinter SetBold error');
        }
    }

    /**
     * 设置对齐类型
     * @param {number} type 0=左对齐, 1=居中对齐, 2=右对齐
     */
    async SetAlignType(type) {
        if(this.printer == null) {
            await this.InitAsync();
        }
        let ret = await this.printer.setAlignType(type);
        if(!ret) {
            throw new Error('SiupoPrinter SetAlignType error');
        }
    }

    /**
     * 设置行间距
     * @param {number} n 字符行高度(单位1点，1点=0.125mm)
     */
    async SetLineSpace(n) {
        if(this.printer == null) {
            await this.InitAsync();
        }
        let ret = await this.printer.setLineSpace(n);
        if(!ret) {
            throw new Error('SiupoPrinter SetLineSpace error');
        }
    }

    async Print(str) {
        if(this.printer == null) {
            await this.InitAsync();
        }
        let ret = await this.printer.print(str);
        if(!ret) {
            throw new Error('SiupoPrinter Print error');
        }
    }

    /**
     * 打印二维码
     * @param {number} w 二维码横纵放大倍数(一般为 4 或 5)
     * @param {string} str 二维码数据字符串
     */
    async PrintQR(w, str) {
        if(this.printer == null) {
            await this.InitAsync();
        }
        let ret = await this.printer.printQR(w, str);
        if(!ret) {
            throw new Error('SiupoPrinter PrintQR error');
        }
    }

    async CutOff() {
        if(this.printer == null) {
            await this.InitAsync();
        }
        let ret = await this.printer.cutoff();
        if(!ret) {
            throw new Error('SiupoPrinter CutOff error');
        }
    }

    /**
     * 进纸
     * @param {number} lines 向前喂纸空点行数(单位 0.125mm)
     */
    async FeedLines(lines) {
        if(this.printer == null) {
            await this.InitAsync();
        }
        let ret = await this.printer.feedLines(lines);
        if(!ret) {
            throw new Error('SiupoPrinter FeedLines error');
        }
    }
}
/** 金诚信id读卡器 */
export class IDCardReader {
    constructor() {
        let terminfo=sessionStorage.getItem("terminfo");
        let termjson=JSON.parse(terminfo);
        for( let item of termjson) {
            if(item.deviceType==3){
              this.port=item.port;
              this.baudrate=parseInt(item.bps);
              break;
            }
         }
        var sfzSerialno=termjson.sfzSerialno;
        var sfzBaudrate=termjson.sfzBaudrate;
        this.cardReader = null;
		// -------------------------------------------
        // this.port = "SDT_USB";//;
        // this.baudrate =parseInt("9600");//;
        this.name = "GHCIDReader";
    }
    async InitAsync() {
        if(typeof(CefSharp) == 'undefined') {
            console.error("CefSharp is undefined.")
            throw "CefSharp is undefined.";
        } else {
            if(typeof(GHCIDReader) == 'undefined') {
                await CefSharp.BindObjectAsync(this.name);
            }
        }
        this.cardReader = GHCIDReader;
    }

    async Open() {

    }

    async Close() {
        this.cardReader.close();
        this.cardReader = null;
    }

    /**
     * @returns {IdInfo}
     */
    async Read() {
        await this.InitAsync();
        let ret = await this.cardReader.open(this.port, this.baudrate);
        if (!ret) {
            LogError(`打开串口${this.port}失败`);
            throw `打开串口${this.port}失败`;
        }else{
            let value = await this.cardReader.readId();
            let info = JSON.parse(value);
            let idInfo = new IdInfo();
            idInfo.clone(info);
            if(info.ID == '') {
                LogError('未读到身份证信息');
                return idInfo;
            } else {
                LogInfo('Read: ' + value);
                return idInfo;
            }
        }
    }
}
/** 握奇2160读卡器 */
export class WQReader {
    constructor() {
        this.cardReader = null;
        this.port = "SDT_USB";
        this.name = "W2160";
    }

    async InitAsync() {
        if(typeof(CefSharp) == 'undefined') {
            console.error("CefSharp is undefined.")
            throw "CefSharp is undefined.";
        } else {
            if(typeof(W2160) == 'undefined') {
                await CefSharp.BindObjectAsync(this.name);
            }
        }
        this.cardReader = W2160;
    }

    async Open() {
        await this.InitAsync();
        let ret = this.cardReader.open(this.port);
        if (!ret) {
            LogError(`打开握奇读卡器${this.port}失败`);
            throw `打开握奇读卡器${this.port}失败`;
        }
    }
 /**
     * 初始化
     * @param {string} BlockNum 块区 0x08
     * @param {number} Key  密码默认“FFFFFFFFFFFF”
     */
    async Init(BlockNum,Key) {
        if(this.cardReader == null) {
            await this.InitAsync();
        }
        let ret = await this.cardReader.set(BlockNum,Key);
       return ret;
    }

    /**
     * @returns {cardId}
     */
    async Read() {
        let value = await this.cardReader.readCard();
        console.log("value="+value);
        if(value == '') {
            LogError('读卡失败');
            return value;
        } else {
            LogInfo('Read: ' + value);
            return value;
        }
    }
      /**
     * @returns {cardId}
     */
    async readCardId() {
        if(this.cardReader == null) {
            await this.InitAsync();
        }
		console.log(this.cardReader)
        let value = await this.cardReader.readCardId();
        console.log("value="+value);
        if(value == '') {
            LogError('读卡失败');
            return value;
        } else {
            LogInfo('Read: ' + value);
            return value;
        }
    }
}
/** 四合一读卡器 */
export class FourInOneReader {
    constructor() {
        this.cardReader = null;
        this.name = "FourInOneCardReader";
    }

    async InitAsync() {
        if(typeof(CefSharp) == 'undefined') {
            console.error("CefSharp is undefined.")
            throw "CefSharp is undefined.";
        } else {
            if(typeof(FourInOneCardReader) == 'undefined')
            await CefSharp.BindObjectAsync(this.name);
        }
        this.cardReader = FourInOneCardReader;
    }

    async Open() {
        await this.InitAsync();
        let ret = this.cardReader.open();
        if (!ret) {
            LogError(`打开四合一读卡器失败`);
            throw `打开四合一读卡器失败`;
        }
    }
        /**
     * 非接卡读卡set
     * @param {string} Secnr 扇区号1~16
     * @param {string} Mode 秘钥类型，60 A秘钥。61 B 秘钥
     * @param {string} key 秘钥
     */
    async Set(Secnr,Mode,key) {
        if(this.cardReader == null) {
            await this.InitAsync();
        }
        let ret = this.cardReader.set(Secnr,Mode,key);//('1','60','FFFFFFFFFFFF');
         return ret;
    }
     /**
     * 非接卡读卡获取卡id
     * @param {String}  0~63
     */
    async getCardId(){
        if(this.cardReader == null) {
            await this.InitAsync();
        }
        let ret = this.cardReader.readCardId("0");
        if(ret== '') {
            LogError(`获取卡iD失败`);
            throw `获取卡iD失败`;
        }
        else {
            LogInfo('ret: ' + ret);
        }
        return ret;
    }
    async Close() {
        this.cardReader.close();
        this.cardReader = null;
    }
    /**
     * @returns {IdInfo}
     */
    async ReadId() {
        let value = await this.cardReader.readId();
        let info = JSON.parse(value);
        if(info.ID == '') {
            LogError('未读到身份证信息');
        } else {
            LogInfo('Read: ' + value);
        }
        return info;
    }
}

/** 九台壁挂打印机 */
export class PosPrinter {
    constructor() {
        this.printer = null;
        this.name = 'GeneralPrinter';
    }

    async InitAsync() {
        if(typeof(CefSharp) == 'undefined') {
            console.error("CefSharp is undefined.")
            throw "CefSharp is undefined.";
        } else {
            if(typeof(GeneralPrinter) == 'undefined')
            await CefSharp.BindObjectAsync(this.name);
        }
        this.printer = GeneralPrinter;
    }

    /**
     * 添加文字
     * @param {string} str
     * @param {number} fontSize 推荐值10 - 14
     * @param {boolean} isBold
     * @param {number} align 对齐 0,1,2对应左中右
     */
    async AppendStr(str, fontSize, isBold, align) {
        if(this.printer == null) {
            await this.InitAsync();
        }
        await this.printer.appendStr(str, fontSize, isBold, align);
    }

    /**
     * 添加二维码
     * @param {string} code
     * @param {number} multiple 放大倍数 推荐-3
     * @param {number} align 对齐 0,1,2对应左中右
     */
    async AppendQr(code, multiple, align) {
        if(this.printer == null) {
            await this.InitAsync();
        }
        await this.printer.appendQr(code, multiple, align);
    }

    /** 打印 */
    async Print(name) {
        if(this.printer == null) {
            await this.InitAsync();
        }
        await this.printer.print(name);
    }
}


/** 吉大口腔银行卡读卡器*/
/** 创自310读卡器 */
export class CZReader {
    constructor() {
        // let terminfo=sessionStorage.getItem("terminfo");
        // let termjson=JSON.parse(terminfo);
        // for( let item of termjson) {
        //     if(item.devtype=="4"){
        //         break;
        //     }
        // }
        this.port="COM3";
        this.baudrate="9600";
        this.cardReader = null;
        // 端口打开标志
        this.isInitPort = false;
        // 设置读卡类型标志
        this.isInitCardType = false;
        // 读卡位置设置
        this.isInitPosition = false;
        this.name = "Crt310CardReader";
    }

    async InitAsync() {
        if(typeof(CefSharp) == 'undefined') {
            console.error("CefSharp is undefined.");
            throw "CefSharp is undefined.";
        } else {
            if(typeof(Crt310CardReader) == 'undefined'){
                await CefSharp.BindObjectAsync(this.name);
            }

        }
        this.cardReader = Crt310CardReader;
    }

    /**
     * 打开端口
     * @returns {Promise<void>}
     * @constructor
     */
    async Open() {
        await this.InitAsync();
        let ret = await this.cardReader.open(this.port,this.baudrate);
        if (!ret) {
            LogError(`打开创自读卡器${this.port}失败`);
            throw `打开创自读卡器${this.port}失败`;
        }
       this.isInitPort = true;
    }

    /**
     * 卡复位（退卡）
     * 0:不弹卡 1：前端弹卡  2：后端弹卡
     *
     */
    async Init(Key) {
        let ret = await this.cardReader.cardReset(Key);
        return ret;
    }

    /**
     * 设置允许进卡（卡类型）
     * key: 1:不允许进卡  2：磁条卡  3；磁条、IC、M1  4：磁信号
     * 当前银行卡应该是IC卡
     * hd:0：允许后端进卡  1：不允许
     */
    async cardSetting(Key,hd) {
        let ret = await this.cardReader.cardSetting(Key,hd);
        this.isInitCardType = true;
        return ret;
    }
    /**
     * 停卡位置
     * position: 1:前端不持卡  2：前端持卡  3；M1读卡位  4：IC读卡位 5：后端持卡  6：后端不持卡
     */
    async cardPosition(position) {
        let ret = await this.cardReader.cardPosition(position);
        this.isInitPosition = true;
        return ret;
    }
    /**
     * 移动卡
     * position: 1:前端不持卡  2：前端持卡  3；M1读卡位  4：IC读卡位 5：后端持卡  6：后端不持卡  7:回收卡   8：卡清洁
     */
    async movePosition(mposition) {
        let ret = await this.cardReader.movePosition(mposition);
        return ret;
    }
    /**
     * 获取状态
     *
     */
    async getStatus() {
        let ret = await this.cardReader.getStatus();
        console.log("获取读卡器状态：");
        console.log(ret);
        return ret;
    }

    /**
     * 读磁条卡
     */
    async readTrackCard(key) {
        let value = await this.cardReader.readTrackCard(key);
        console.log("value="+value);
        return value;
    }

    /**
     *  读IC卡
     * @param key
     * @returns {Promise<*>}
     */
    async Read(){
        // 打开端口
        if(this.isInitPort == false){
            this.Open();
        }
        // 设置读卡类型
        if(this.isInitCardType == false){
          this.cardSetting(3,0);
        }
        // 设置停卡位置
        if(this.isInitPosition == false){
          this.cardPosition(4);
        }
        console.log("开始读卡：...........................银行卡...............................");
        let valueRCID = await this.cardReader.getCardId();
        console.log("valueRCID="+valueRCID);
        let valueRC = await this.cardReader.readCard();
        console.log("valueRC="+valueRC);
        console.log("读卡完毕：...........................银行卡...............................");
        return valueRC;
    }

    async returnCard(){
        console.log("退卡：...........................银行卡...............................");
        let returnC = await this.Init(1);
        console.log("退卡完毕：...........................银行卡...............................");
        return returnC;
    }

    /**
     * 关闭
     *
     */
    async close() {
        let ret = await this.cardReader.close();
        return ret;
    }
}

/**CUSTOMK80热敏打印机 */
export class CK80Printer {
    constructor() {
        let terminfo=sessionStorage.getItem("terminfo");
        let termjson=JSON.parse(terminfo);
        for( let item of termjson) {
            if(item.deviceType=="2"){
              this.port=item.port;
              this.baudrate=item.bps;
              break;
            }
         }

        this.printer = null;
        this.name = 'K80Printer';
    }

    async InitAsync() {
        if(typeof(CefSharp) == 'undefined') {
            console.error("CefSharp is undefined.")
            throw "CefSharp is undefined.";
        } else {
            if(typeof(GeneralPrinter) == 'undefined')
            await CefSharp.BindObjectAsync(this.name);
        }
        this.printer = K80Printer;
    }
      /**
     * @param {number} mode
     * @param {number} mode
     */
    async Open() {
        await this.InitAsync();
        let ret = await this.printer.open(this.port, parseInt(this.baudrate));
        if (!ret) {
            LogError(`打开串口${this.port}失败`);
            throw new Error(`打开串口${this.port}失败`);
        }
    }
     /**
     *  @returns {status}
     * 获取打印机状态
     */
    async GetStatus() {
        if(this.printer == null) {
            await this.InitAsync();
        }
        let ret = await this.printer.open(this.port, parseInt(this.baudrate));
        if (!ret) {
            LogError(`打开串口${this.port}失败`);
            throw new Error(`打开串口${this.port}失败`);
        }
        else{
            var status= await this.printer.getPrintStatus();
            console.log("status="+status);
            await this.printer.close();
            switch(parseInt(status)){
                case 0:status="0";break;
                case 1:status="打印机缺纸，请换台终端或者联系管理员处理！";break;
                case 2:status="2";break;
                case 3:status="打印机卡纸，请换台终端或者联系管理员处理！0";break;
                case 4:status="打印机出纸口有纸，请换台终端或者联系管理员处理！";break;
                case 5:status="打印机盖盒未关闭，请换台终端或者联系管理员处理！0";break;
                case 6:status="打印机过热，请换台终端或者联系管理员处理！";break;
            }
            LogInfo('Read: ' + status);
            return status;
        }

    }
    /**
     * 设置文字样式： 0，1,2，8，10,20，40,80
     * @param {number} mode
     */
    async SetMode(mode) {
        if(this.printer == null) {
            await this.InitAsync();
        }
        await this.printer.setTextMode(mode);
    }

    /**
     * 设置文字大小： 0：正常字体   17：字体加大
     * @param {number} mode
     */
    async selectCharacterSize(mode) {
        if(this.printer == null) {
            await this.InitAsync();
        }
        await this.printer.selectCharacterSize(mode);
    }

        /**
     * 打印二维码
     * @param {string} mode ：二维码数据
     */
    async PrintQR(mode,size) {
        if(this.printer == null) {
            await this.InitAsync();
        }
        // await this.printer.addBitmap(mode,0);
        await this.printer.addBitmap(mode,size);
    }
      /**
     * 设置位置
     * @param {string} mode ：left ,center,right.
     */
    async Setweizhi(mode) {
        if(this.printer == null) {
            await this.InitAsync();
        }
        await this.printer.setJustify(mode);
    }

    /**
     * 行间距
     * @param {number} lines
     */
    async SetLines(lines) {
        if(this.printer == null) {
            await this.InitAsync();
        }
        await this.printer.skipLines(lines);
    }
      /**
     * 赋值打印内容
     * @param {string} str
     */
    async AppendStr(str) {
        if(this.printer == null) {
            await this.InitAsync();
        }
        await this.printer.writeLine(str);
    }
      /**
     * 切纸
     */
    async CutOff() {
        if(this.printer == null) {
            await this.InitAsync();
        }
        await this.printer.cutOff();
    }
      /**
     * 关闭打印机
     */
    async Close() {
        if(this.printer == null) {
            await this.InitAsync();
        }
        await this.printer.close();
    }
}
export class IdInfo {
    constructor() {
        /**
         * @type {string}
         */
        this.Name = "";
        this.Sex = "";
        this.Nation = "";
        this.Birthday = "";
        this.Address = "";
        this.ID = "";
        this.GrantDept = "";
        this.EffectiveDate = "";
        this.ExpirationDate = "";
        this.ErrMsg = "";
        this.Result = "";
    }

    clone(obj) {
        this.Name = obj.name;
        this.Sex = obj.gender;
        this.Nation = obj.nation;
        this.Birthday = obj.birthday;
        this.Address = obj.address;
        this.ID = obj.cardID;
        this.GrantDept = obj.issuingOrg;
        this.EffectiveDate = obj.validStart;
        this.ExpirationDate = obj.validEnd;
        //this.ErrMsg = obj.ErrMsg;
        //this.Result = obj.Result;
    }
}


function LogInfo(str) {
    console.log(str);
}

function LogDebug(str) {
    console.log(`%c ${str}`, 'color:blue');
}

function LogError(str) {
    console.log(`%c ${str}`, 'color:red');
}

function LogWarn(str) {
    console.log(`%c ${str}`, 'color:yellow');
}
